#include "CTS.h"

CTS::CTS(const char* chArray)
{
	memcpy(m_data, chArray, 188);
	_parseTsHeader();
}

CTS::~CTS(void)
{
}

const char* CTS::getPayload()
{
	return m_data + m_headerLength;
}
unsigned int CTS::getHeaderLength()
{
	return m_headerLength;
}
unsigned int CTS::getPayloadLength()
{
	return 188-m_headerLength;
}
char* CTS::getData()
{
	return m_data;
}
unsigned int CTS::getContinuityCounter()
{
	return m_continuity_counter;
}
unsigned int CTS::getPID()
{
	return m_PID;
}
unsigned int CTS::getPayloadStartIndicator()
{
	return m_payload_unit_start_indicator;
}
unsigned int CTS::getAdaptationFieldControl()
{
	return m_adaptation_field_control;
}
unsigned long long CTS::getPCR()
{
	return m_program_clock_reference_base;
}

void CTS::_parseTsHeader()
{
	//extract some of the TS header fields
	m_PID = (unsigned int)m_data[2] & 0xff;
	m_payload_unit_start_indicator  = ((unsigned int)m_data[1] & 0x40)/64;
	m_continuity_counter = ((unsigned int)m_data[3] & 0xff) & 0xf;
	m_adaptation_field_control = ((unsigned int)m_data[3] & 0x30)/16;
	m_PCR_flag = false;
	m_program_clock_reference_base = 0;

	m_headerLength= 4;
	//adaptation field
	if (m_adaptation_field_control==2 || m_adaptation_field_control==3)
	{
		int adaptation_field_length = m_data[4];
		if (adaptation_field_length > 0)
		{
			//PCR
			m_PCR_flag = (bool)((m_data[5] & 0x10)/16);
			if (m_PCR_flag)
			{
				unsigned long long  pcr_base = 0;
				pcr_base += m_data[6];
				pcr_base = pcr_base << 8;
				pcr_base += m_data[7];
				pcr_base = pcr_base << 8;
				pcr_base += m_data[8];
				pcr_base = pcr_base << 8;
				pcr_base += m_data[9];
				pcr_base = pcr_base << 1;
				pcr_base += ((m_data[10] & 0x80) >> 7);
				m_program_clock_reference_base = pcr_base;
			}
		}
		m_headerLength=m_headerLength+adaptation_field_length + 1;
	}
}


bool CTS::isNextTo(int ContinuityCounter){
	//return true if the continuity counter number are continuos
	return (m_continuity_counter == ContinuityCounter + 1) ||
		((m_continuity_counter==0)&&(ContinuityCounter==15));
}
